﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace DotNetUI.Extensions
{
    /// <summary>
    /// 图片服务
    /// </summary>
    public static class VisualExtension
    {
        /// <summary>
        /// 保存到文件
        /// </summary>
        /// <param name="frameworkElement"></param>
        /// <param name="fileName"></param>
        public static void SaveToImage(this FrameworkElement frameworkElement, string fileName)
        {
           var source=  PresentationSource.FromVisual(frameworkElement);
            using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
            {
                var rect = new Rect(0,0,frameworkElement.ActualWidth,frameworkElement.ActualHeight);
                var visual = new DrawingVisual();
                using (var dc = visual.RenderOpen())
                {
                    dc.DrawRectangle(new VisualBrush(frameworkElement), null, rect);
                }
                RenderTargetBitmap bitmap = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 96d* source.CompositionTarget.TransformToDevice.M11, 96d* source.CompositionTarget.TransformToDevice.M22, PixelFormats.Pbgra32);
                bitmap.Render(visual);

                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                encoder.Save(fileStream);
                fileStream.Close();
            }
        }
    }
}
